package stp2;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import se.datadosen.component.RiverLayout;

public class AddDownloadFrame extends Thread implements WindowListener{

	
	
	private ActionListener al;
	private JFrame frame;
	private String title;
	private JTextField saveto;
	private JTextField getvideo;
	private URL dl;
	
	public AddDownloadFrame(ActionListener al){
		this.al = al;
		frame = new JFrame("Add new Youtube download");
		frame.addWindowListener(this);
		Container c = frame.getContentPane();
		c.add(new DownPanel());
		
		frame.pack();
		frame.setVisible(true);
	}
	
	public Download getDownload(){
		frame.setVisible(false);
		frame.dispose();
		return new Download(title,dl,saveto.getText());
	}
	
	public void windowActivated(WindowEvent arg0) {}
	public void windowClosed(WindowEvent arg0) {}
	public void windowClosing(WindowEvent arg0) {
		al.actionPerformed(new ActionEvent(this,ActionEvent.ACTION_PERFORMED,""));
	}
	public void windowDeactivated(WindowEvent arg0) {}
	public void windowDeiconified(WindowEvent arg0) {}
	public void windowIconified(WindowEvent arg0) {}
	public void windowOpened(WindowEvent arg0) {}
	
	private class DownPanel extends JPanel implements KeyListener {

		private static final long serialVersionUID = 1L;
		private JTextField youtubeurl;
		private JLabel status;

		private String sep = System.getProperty("file.separator");
		private CheckURL checkthread;

		private JButton download;
		
		public DownPanel(){
			
			setLayout(new RiverLayout());
			
			youtubeurl = new JTextField("Paste youtube's video url here.",70);
			youtubeurl.setBackground(Color.ORANGE);
			youtubeurl.addKeyListener(this);
			
			status = new JLabel("<html><b>Here you'll see the url checking status.</b></html>");
			
			String path = DownloadManager.path; /*System.getProperty("java.class.path");
			if(path.endsWith("\\YDM.jar")){
				path = path.replace("\\YDM.jar", "");
			}
			if(path.startsWith("YDM.jar")) path = "";*/
			saveto = new JTextField(path+sep+"videos"+sep,70);
			saveto.setEditable(false);
			
			getvideo = new JTextField("Still not found...",70);
			getvideo.setEditable(false);
			
			download = new JButton("Start download");
			download.setEnabled(false);
			download.setActionCommand("START DOWNLOAD");
			download.addActionListener(al);
			
			
			add(new JLabel("Youtube's video url to download:"));
			add("br",youtubeurl);
			add("br",status);
			add("br",new JLabel("Video will be saved here:"));
			add("br",saveto);
			add("br",new JLabel("Video will be downloaded from:"));
			add("br",getvideo);
			add("br",download);
			
			
		}

		private String inputStreamToString(InputStream is){
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String html = "";

			while(true){

				try {
					String t = br.readLine();
					if(t == null) break;
					html += t;
				} catch (IOException e) {
					break;
				}

			}
			return html;
			
		}
		private String getVideoTitle(InputStream is){
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String html = "";

			while(true){

				try {
					String t = br.readLine();
					if(t == null) break;
					html += t;
					if(t.matches("<title>")) break;
					
				} catch (IOException e) {
					break;
				}

			}
			String t = html.split("<title>YouTube - ")[1].split("</title>")[0];
			String p = "";
			for(int i =0; i < t.length(); i++){
				char c = t.charAt(i);
				if((c >='a' && c <='z') || (c >='A' && c <='Z') || (c >='0' && c <='9')){
					p += c+"";
				} else p +="_";
			}
			return p;
			
		}



		public void keyReleased(KeyEvent arg0) {
			if(checkthread == null || !checkthread.isAlive()){
			checkthread = new CheckURL();
			checkthread.start();
			}
			
		}

		private class CheckURL extends Thread {
			public void run(){
				String url = youtubeurl.getText();
				download.setEnabled(false);
				if(url.startsWith("http://")){
					if(url.startsWith("http://youtube.com/watch?v=") || url.startsWith("http://www.youtube.com/watch?v=")){
						youtubeurl.setBackground(Color.ORANGE);
						status.setText("<html><font color=\"#ffa500\"><b>Checking url... (Getting video's name)</b></font></html>");
						try {
							URL youtube = new URL(url);
							InputStream is = youtube.openConnection().getInputStream();
							title = getVideoTitle(is);
							//title = html.split("<title>YouTube - ")[1].split("</title>")[0];
							String path = DownloadManager.path; /*System.getProperty("java.class.path");
							if(path.endsWith("\\YDM.jar")){
								path = path.replace("\\YDM.jar", "");
							}
							if(path.startsWith("YDM.jar")) path = "";*/
							String st = path+sep+"videos"+sep+title+".flv";
							saveto.setText(st);					
							
						} catch (MalformedURLException e) {
							youtubeurl.setBackground(Color.RED);
							status.setText("<html><font color=\"red\"><b>Ivalid url.</b></font></html>");
						} catch (IOException e) {
							youtubeurl.setBackground(Color.RED);
							status.setText("<html><font color=\"red\"><b>Can't connect to url to get video's name.</b></font></html>");
						} catch(ArrayIndexOutOfBoundsException e){
							youtubeurl.setBackground(Color.RED);
							status.setText("<html><font color=\"red\"><b>Can't find video's name from html document.</b></font></html>");
						}
						youtubeurl.setBackground(Color.ORANGE);
						status.setText("<html><font color=\"#ffa500\"><b>URL OK. Video's name found. Trying to find video's download url from 'http://www.videodownloader.net' ...</b></font></html>");

						try {
							String result = "http://videodownloader.net/get/?url="+parseReserved(url);
							URL vd = new URL(result);
							InputStream is = vd.openConnection().getInputStream();
							String html = inputStreamToString(is);
							String query = html.split("<a href=\"http://youtube.com/get_video")[1].split("\">")[0];
							dl = new URL("http://youtube.com/get_video"+query);
							getvideo.setText("http://youtube.com/get_video"+query);
							youtubeurl.setBackground(Color.GREEN);
							status.setText("<html><font color=\"green\"><b>Ready to download. Please, push \"Start download\" button.</b></font></html>");
							download.setEnabled(true);
							
						} catch (MalformedURLException e) {
							youtubeurl.setBackground(Color.RED);
							status.setText("<html><font color=\"red\"><b>Ivalid 'videodownloader.net' url.</b></font></html>");
						} catch (IOException e) {
							youtubeurl.setBackground(Color.RED);
							status.setText("<html><font color=\"red\"><b>Can't connect to 'videodownloader.net'.</b></font></html>");
						} catch(ArrayIndexOutOfBoundsException e){
							youtubeurl.setBackground(Color.RED);
							status.setText("<html><font color=\"red\"><b>Can't find video's download url from 'videodownloader.net'.</b></font></html>");
						}
						
						
						
						
					}else{
						youtubeurl.setBackground(Color.RED);
						status.setText("<html><font color=\"red\"><b>URL should begin with 'http://youtube.com/watch?v='.</b></font></html>");

					}
				}else{
					youtubeurl.setBackground(Color.RED);
					status.setText("<html><font color=\"red\"><b>URL should begin with 'http://'.</b></font></html>");
				}
			
			}
			private String parseReserved(String g){
				String r = "";
				for(int i = 0; i< g.length(); i++){
					if(escape(g.charAt(i))){
						r += "%"+Integer.toHexString(g.charAt(i)).toUpperCase();
					}else{
						r += g.charAt(i)+"";
					}
				}
				return r;
			}
			private boolean escape(char c){
				
				if(c >= 'A' && c <= 'Z') return false;
				if(c >= 'a' && c <= 'z') return false;
				if(c >= '0' && c <= '9') return false;
				
				return true;
				
			}
		}

		public void keyTyped(KeyEvent arg0) {}
		public void keyPressed(KeyEvent arg0) {}
		
	}
	
}
